﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using YonYou.U8.IN.Forms;
using YonYou.U8.IN.Framework.Provider;
using YonYou.U8.IN.Framework.Views;
using YonYou.U8.IN.Model;
using YonYou.U8.IN.Utility;

namespace YonYou.U8.IN.Framework.Actions
{
    internal class ToolBarInitialize : IViewAction
	{
		public object Execute(params object[] args)
		{
			Execute(args[0] as ToolBarView);
			return null;
		}

		protected virtual void Execute(ToolBarView view)
		{
			if (view == null)
			{
				throw new ArgumentNullException("view");
			}
			MetroToolBar toolBar = view.Control as MetroToolBar;
			LoadToolBarMenu(toolBar, view.ItemCache);
		}

		/// <summary>
		/// 加载按钮图标
		/// </summary>
		/// <param name="toolBar"></param>
		/// <param name="itemCache"></param>
		private void LoadToolBarMenu(MetroToolBar toolBar, Hashtable itemCache)
		{
			try
			{
				MenuProvider menuProvider = new MenuProvider();
				BizMenuNode bizMenuNode = menuProvider.Get(LoginEntity.ufsysconnstr); //ViewAdvisor.Instance.Context.LoginEntity.UFSysConnectionStr);
				FrameworkContext frameworkContext = ViewAdvisor.Instance.Context as FrameworkContext;
				frameworkContext.RootMenuNode = bizMenuNode;
				foreach (BizMenuNode item in bizMenuNode)
				{
                    #region	修改dll路径便于调式

                    string asm = item.Data.Assembly;
					if(!string.IsNullOrEmpty(asm))
					{
						int i=asm.IndexOf("ImplementNavigation",StringComparison.OrdinalIgnoreCase);
						if (i >= 0)
						{
                            item.Data.Assembly = item.Data.Assembly.Replace("ImplementNavigation\\", "");
                        }
                        i = asm.IndexOf("QuickImport", StringComparison.OrdinalIgnoreCase);
                        if (i >= 0)
                        {
                            item.Data.Assembly = item.Data.Assembly.Replace("QuickImport\\", "");
                        }
                        i = asm.IndexOf("BusinessNavigation", StringComparison.OrdinalIgnoreCase);
                        if (i >= 0)
                        {
                            item.Data.Assembly = item.Data.Assembly.Replace("BusinessNavigation\\", "");
                        }
                    }
                    
					#endregion

                    MetroToolItem metroToolItem = new MetroToolItem();
					string name = Path.Combine(PathUtils.INPath, item.Data.ImagePath);
					metroToolItem.Image = ImageUtils.GetImageFromLocal(name);
					metroToolItem.Text = item.Data.Name;
					metroToolItem.Tag = item;
					if (!itemCache.ContainsKey(item.Data.Id))
					{
						itemCache.Add(item.Data.Id, metroToolItem);
						((List<MetroToolItem>)(object)toolBar.Items).Add(metroToolItem);
					}
				}
			}
			catch (Exception ex)
			{
				Debug.WriteLine("[实施导航]-[ToolBarInitialize->LoadToolBarMenu()]-[StackTrace:{0}]-[Message:{1}]", ex.StackTrace, ex.Message);
			}
		}
	}
}
